package file_handle

import (
	"encoding/json"
	"fmt"
	log "github.com/sirupsen/logrus"
	"gopkg.in/yaml.v3"
	"os"
)

// exists returns whether the given file or directory exists or not
func Exists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return true, err
}

// GenerateConfigYamlFile 生成yaml配置文件
func GenerateConfigFile(Conf any, outFilePath string) (flag bool) {
	data, err := yaml.Marshal(Conf)
	if err != nil {
		fmt.Errorf("failed to marshal config: %v", err)
		return false
	}
	err = os.WriteFile(outFilePath, data, 0644)
	if err != nil {
		fmt.Errorf("failed to write config file: %v", err)
		return false
	}
	return true
}

func SaveJsonFile(Conf any, filePath string) error {
	exist, err := Exists(filePath)
	if err != nil {
		log.Error("failed to check if file exists: %v", err)
		return err
	}

	var file *os.File
	if !exist {
		file, err = os.Create(filePath)
		if err != nil {
			return err
		}
		defer file.Close()
	} else {
		file, err = os.OpenFile(filePath, os.O_WRONLY|os.O_TRUNC, 0644)
		if err != nil {
			return err
		}
		defer file.Close()
	}

	encoder := json.NewEncoder(file)
	encoder.SetIndent("", "    ") // 设置缩进，使JSON文件更易读
	return encoder.Encode(Conf)
}

func ReadJsonFile(filePath string, Conf any) error {
	file, err := os.Open(filePath)
	if err != nil {
		return err
	}
	defer file.Close()

	decoder := json.NewDecoder(file)
	return decoder.Decode(Conf)
}
